package com.livegoods.service;

import com.livegoods.commons.pojo.LivegoodsResult;
import com.livegoods.dao.HouseDao4MongoDB;
import com.livegoods.dao.HouseDao4Redis;
import com.livegoods.pojo.House;
import com.livegoods.pojo.Order;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

@Service
public class BuyactionServiceImpl  implements BuyactionService{


    /**
     *
     * 房屋预定抢购方法，此方法有三个功能
     *
     * 0，从Redis中获取对应房屋
     *
     * 1，修改Redis中房屋租赁状态 isRent=false （已出租）
     *
     * 2，修改MongoDB中房屋租赁状态 isRent=false （已出租）
     *
     * 3，创建订单信息,生成订单数据
     *
     *
     *
     *
     * @param houseId
     * @param username
     * @return
     */

    @Value("${livegoods.redis.houseKey}")
    private String livegoodsRedisHouseKey;


    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private HouseDao4Redis houseDao4Redis;

    @Autowired
    private HouseDao4MongoDB houseDao4MongoDB;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public boolean buyHouse(String houseId, String username) {

        //0，从Redis中获取对应房屋
        String redisKey = livegoodsRedisHouseKey+":"+houseId;

        House house = houseDao4Redis.get(redisKey);

        //1，修改Redis中房屋租赁状态 isRent=false （已出租）
        house.setIsRent(false);
        //Redis中修改房屋状态isRent 为出租状态
        boolean flag = houseDao4Redis.set(redisKey, house);
        System.out.println("出租状态 = " + flag);

        if (flag){
            //2，修改MongoDB中房屋租赁状态 isRent=false （已出租）
            long row = houseDao4MongoDB.update(houseId);
            System.out.println("row = " + row);

            if (row == 1){
                //3，创建订单信息,生成订单数据
                Order order = new Order();
                order.setHouseId(houseId);
                order.setHouseType(house.getHouseType());
                order.setTitle(house.getTitle());
                order.setPrice(house.getPrice());
                order.setImg(house.getImgs().get(0));
                order.setRentType(house.getRentType());
                order.setUsername(username);
                order.setCommentState(0);//设置0 未评论

                //新增订单数据
                order = mongoTemplate.save(order);

                if (order.getId()!=null){
                    return true;
                }

            }
        }
        return false;
    }
}
